<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Orders extends Vip_Controller
{
    function __construct ()
    {
        parent::__construct();
        $this->load->model('good_m');
        $this->load->model('shop_m');
        $this->load->model('order_m');
        $this->load->model('user_m');
        $this->load->model('delivers_m');
        $this->load->model('message_m');
        $this->load->library('pagination');

        $this->load->model('category_m');
        $this->load->model('member_m');
        $this->load->model('areas_m');
        $this->load->model('tmporder_m');
        $this->uid = $this->session->userdata('user_id');
    }
    /**
     * 列表
     * [index description]
     * @return [type] [description]
     */
    public function index($page=1)
    {
       
        $limit = 20;
        $config['uri_segment'] = 4;
        // $page = !empty($config['uri_segment'])?$config['uri_segment']:'0';
        $config['use_page_numbers'] = TRUE;
        $config['base_url'] = site_url('manage/orders/index/');
        if($this->auth->is_super_admin()){
            $config['total_rows'] = $this->db->count_all('shop_orders');
        }else{
            $config['total_rows'] = $this->db->where("user_id",$this->uid)->count_all('shop_orders');
        }
        $config['per_page'] = $limit;
        $config['num_links'] = 10;
        $this->pagination->initialize($config);
        $start = ($page-1)*$limit;
        $data['pagination'] = $this->pagination->create_links();
        if($this->auth->is_super_admin()){
            $orders = $this->order_m->get_all_orders($start,$limit);
        }else{
            $orders = $this->order_m->get_all_orders($start,$limit,$this->uid);
        }
        if(!empty($orders)){
            foreach($orders as $key=>$val){
                $goodinfo = $this->good_m->get_shop_goods_by_id($val['good_id']);
                $shopinfo = $this->shop_m->get_shop_user_by_id($val['shop_id']);
                $userinfo = $this->user_m->get_user_by_user_id($val['user_id']);
                $orders[$key]['good_title'] = $goodinfo['good_title'];
                $orders[$key]['shop_title'] = $shopinfo['shop_title'];
                $orders[$key]['user_name'] = $userinfo['user_name'];
            }
        }
//        pp($orders);exit();
        $data['orders'] = $orders;
        $this->load->view('orders/index', $data);

    }
    //查询已发货的订单
    public function order_status($page=1){
        $limit = 20;
        $config['uri_segment'] = 4;
        $config['use_page_numbers'] = TRUE;
        $config['base_url'] = site_url('manage/orders/order_status');
        $config['total_rows'] = $this->order_m->count_all_ings();
        $config['per_page'] = $limit;
        $config['num_links'] = 10;
        $this->pagination->initialize($config);
        $start = ($page-1)*$limit;
        $data['pagination'] = $this->pagination->create_links();
        $orders = $this->order_m->get_delivers($start,$limit);
        if(!empty($orders)){
            foreach($orders as $key=>$val){
                $goodinfo = $this->good_m->get_shop_goods_by_id($val['good_id']);
                $shopinfo = $this->shop_m->get_shop_user_by_id($val['shop_id']);
                $userinfo = $this->user_m->get_user_by_user_id($val['user_id']);
                $orders[$key]['good_title'] = $goodinfo['good_title'];
                $orders[$key]['shop_title'] = $shopinfo['shop_title'];
                $orders[$key]['user_name'] = $userinfo['user_name'];
                
            }
        }
        $data['orders'] = $orders;
        $this->load->view('orders/index', $data);
    }

    //发货
    public function delivers($id){
        if($this->input->post()){
        $data['order_id'] = $id;
        $deliversid = $this->input->post('deliver_company');
        $data['deliver_no'] = $this->input->post('deliver_no');
        $data['deliver_send_time'] = time();
        $deliver=$this->delivers_m->get_delivers_by_id($deliversid);
        $data['deliver_company']=$deliver['deliver_name'];
        $data['deliver_code']=$deliver['deliver_code'];
        $result = $this->delivers_m->add_deliver($data);
        if($result){
            //更改物流状态为已发货
            $arr['order_deliver'] = 2;
            $this->order_m->sava_shop_orders($id,$arr);
            $order_info = $this->order_m->get_shop_orders_by_id($id);
            $order_no = $order_info['order_no'];
            //提现信息存到message表中
            $jlmsg['message_txt'] = '发货成功，您的订单<em>'.$order_no.'</em>已发货。<a href="'.site_url("member/order_logistics/".$id).'">查看物流</a>';
            $jlmsg['message_type'] =10;
            $jlmsg['message_to_uid'] =$order_info['user_id'];
            $jlmsg['message_time'] =time();
            $jlmsg['message_lock'] =1;
            $this->message_m->add_massage($jlmsg);
            show_message('发货成功！',site_url(V_URL.'orders/index'),1);
        }else{
            show_message('发货失败重新发货',site_url(V_URL.'orders/orders/'.$id),1);
        }
        }
        $data['delivers'] = $this->delivers_m->get_all_delivers_comenpty();
        $data['id']=$id;
        $this->load->view('orders/delivers',$data);
    }
    //修改发货
    public function edit_delivers($id=0){
        if($this->input->post()){
            $deliver_id=$this->input->post('deliver_id');
            $deliversid = $this->input->post('deliver_company');
            $data['deliver_no'] = $this->input->post('deliver_no');
            $data['deliver_send_time'] = time();
            $deliver=$this->delivers_m->get_delivers_by_id($deliversid);
            $data['deliver_company']=$deliver['deliver_name'];
            $data['deliver_code']=$deliver['deliver_code'];
            $result = $this->delivers_m->save_deliver($deliver_id,$data);
            if($result){
            //更改物流状态为已发货
                $arr['order_deliver'] = 2;
                $this->order_m->sava_shop_orders($id,$arr);
                show_message('修改发货成功！',site_url(V_URL.'orders/index'),1);
            }
        }
        //根据订单的id查询用户的物流信息
        $data['info'] = $this->delivers_m->get_deliver_by_order_id($id);
        $data['delivers'] = $this->delivers_m->get_all_delivers_comenpty();
        $this->load->view('orders/edit_delivers',$data);

    }
    //查询所有未发货的订单
    public function ordering($page=1){
        $limit = 20;
        $config['uri_segment'] = 4;
        $config['use_page_numbers'] = TRUE;
        $config['base_url'] = site_url('manage/orders/ordering/');
        $config['total_rows'] = $this->order_m->count_all_ing();
        $config['per_page'] = $limit;
        $config['num_links'] = 10;
        $this->pagination->initialize($config);
        $start = ($page-1)*$limit;
        $data['pagination'] = $this->pagination->create_links();
        $orders = $this->order_m->get_delivering($start,$limit);
        if(!empty($orders)){
            foreach($orders as $key=>$val){
                $goodinfo = $this->good_m->get_shop_goods_by_id($val['good_id']);
                $shopinfo = $this->shop_m->get_shop_user_by_id($val['shop_id']);
                $userinfo = $this->user_m->get_user_by_user_id($val['user_id']);
                $orders[$key]['good_title'] = $goodinfo['good_title'];
                $orders[$key]['shop_title'] = $shopinfo['shop_title'];
                $orders[$key]['user_name'] = $userinfo['user_name'];
                
            }
        }
        $data['orders'] = $orders;
        $this->load->view('orders/index', $data);
    }
    //删除失败的订单
    public function del($id){
        $results = $this->order_m->del_order_by_id($id);
        if($results){
            show_message('删除订单成功',site_url(V_URL.'orders/index'),1);
        }

    }

    //查询订单
    public function delivers_show($order_id)
    {
        $data['order_info'] = $this->order_m->get_shop_orders_by_id($order_id);
        $this->load->view('orders/deliver_show', $data);
    }

    /**
     * 发货和支付
     * @param $order_id
     * @return bool
     */
    public function get_status($order_id,$status){

        if(!$order_id){ return false;}
        $info = $this->order_m->get_shop_orders_by_id($order_id);
        if(!empty($info)){
            $return = false;
            if($status == 1){
                // 确认收款
                $return = $this->order_m->sava_shop_orders($order_id,['order_pay'=>1,'order_status'=>1]);
            }
            if($status == 2){
                // 发货
                $return = $this->order_m->sava_shop_orders($order_id,['order_status'=>2]);
                $massage = array(
                    'message_txt'=>"您的订单已经安排送货啦！",
                    'message_to_uid'=>$order_id,
                    'message_time'=>date("Y-m-d H:i:s"),
                );
                $this->message_m->add_massage($massage);
            }
            if($return){
                show_message('操作订单成功',site_url(V_URL.'orders/index'),1);
            }else{
                show_message('操作订单成功',site_url(V_URL.'orders/index'),1);
            }

        }
    }



    /***************************************用户下单*******************************************/

    public function create(){

        if($_POST){
            if(isset($_POST['category_id']) && !empty($_POST['category_id'])){
                $len = count($_POST['category_id']);
                for ($i=0; $i < $len; $i++) {
                    foreach ($_POST as $key => $value) {
                        if(is_array($value)){
                            if(isset($value[$i]) && !empty($value[$i])){
                                $data[$key] = $value[$i];
                            }else{
                                echo json_encode(array(
                                    'status' => 400,
                                    "msg"=>"请完善订单信息",
                                ));
                                exit();
                            }
                        }
                    }
                    $orders[] = $data;
                }
                $order_no = $this->create_order_no();
                $post = $this->input->post();
                if(!isset($post['product_id']) || empty($post['product_id'])){
                    echo json_encode(array(
                        'status' => 400,
                        "msg"=>"请选择产品",
                    ));
                    exit();
                }
                if(!isset($post['good_mum']) || empty($post['good_mum'])){
                    echo json_encode(array(
                        'status' => 400,
                        "msg"=>"请填写产品数量",
                    ));
                    exit();
                }
                if(!empty($orders)) {
                    $order_price = "0";
                    foreach ($orders as $key => $val) {
                        $orders[$key]['user_id'] = $this->uid;
                        // 根据商品id获取商品信息
                        $good = $this->good_m->get_shop_goods_by_id($val['product_id']);
                        $good_total_price = $val['good_mum'] * ($good['good_price'] * 100) / 100;
                        $orders[$key]['good_price'] = $good_total_price;
                        $order_price += $good_total_price;
                        $orders[$key]['order_add_time'] = time();
                        $orders[$key]['order_no'] = $order_no;
                        $this->tmporder_m->add_tmp_orders($orders[$key]);
                    }
                    // 总订单数据
                    $order_data = array(
                        'order_no' => $order_no,
                        'user_id' => $this->uid,
                        'good_price' => $order_price,
                        'order_add_time' => time(),
                    );
                    // 开票费和送货费
                    $order_data['remark'] = !empty($post['remark']) ? $post['remark'] : "";
                    $order_data['good_date'] = !empty($post['good_date']) ? $post['good_date'] : "";
                    $order_data['is_kaipiao'] = $post['is_kaipiao'];
                    $order_data['is_songhuo'] = $post['is_songhuo'];
                    $fee = $order_price;
                    // 服务费一定有
                    $service_fee = $fee * ($this->config->item('service_tax') * 100) / 100; // 服务费一定有
                    $order_data['service_fee'] = $service_fee;
                    $fee = $fee + $service_fee;
                    // 获取送货费
                    if ($order_data['is_songhuo'] == 1) {
                        $orders = $this->tmporder_m->get_tmp_orders_by_order_no($order_no);
                        if (!empty($orders)) {
                            $songhuo_fee = "0";
                            foreach ($orders as $key => $val) {
                                $good = $this->good_m->get_shop_goods_by_id($val['product_id']);
                                $cateinfo = $this->category_m->get_category_by_id($good['good_category']);
                                $good_total_price_row = $val['good_mum'] * ($good['good_price'] * 100) / 100;
                                $songhuo_fee += $good_total_price_row * ($cateinfo['category_tax'] * 100) / 100;
                            }
                            $order_data['songhuo_fee'] = $songhuo_fee;
                            $fee = $fee + $songhuo_fee;
                        }
                    }
                    // 获取开票费,(商品总额+服务费+送货费)*税点
                    if ($order_data['is_kaipiao'] == 1) {
                        $kaipiao_fee = $fee * ($this->config->item('kaipiao_tax') * 100) / 100;
                        $order_data['kaipiao_fee'] = $kaipiao_fee;
                        $fee = $fee + $kaipiao_fee;
                    }
                    // 总订单表记录
                    $order_data['order_price'] = $fee;
                    $order_id = $this->order_m->create_order($order_data);
                    $arr = [
                        [
                            "order_no" => $order_no
                        ],
                        [
                            "order_no" => $order_no,
                            "order_id" => $order_id,
                        ],
                    ];
                    $this->db->update_batch("tmp_orders", $arr, "order_no");
                    echo json_encode(array(
                        'status' => 200,
                        "msg" => "提交成功",
                        "url" => site_url(V_URL . "orders/pay_order/" . $order_no),
                    ));
                    exit();
                }
            }else{
                echo json_encode(array(
                    'status' => 400,
                    "msg"=>"请完善订单信息",
                ));
                exit();
            }
        }
        // 获取默认地址
        $dress=$this->member_m->get_adress_by_user_id($this->uid);
        if(!empty($dress)){
            $area =  $this->areas_m->get_area_by_id($dress['dress_province']);
            $area2 =  $this->areas_m->get_area_by_id($dress['dress_city']);
            $area3 =  $this->areas_m->get_area_by_id($dress['dress_district']);
            $dress['dress_city'] = $area['area_name'].$area2['area_name'].$area3['area_name'].$dress['dress_udress'];
        }else{
            $dress['dress_city'] = "请添加收货地址";
        }
        $data['address'] = $dress;
        // 服务费和开票费
        $data['kaipiao_fee'] = $this->config->item('kaipiao_tax')*100;
        $data['service_tax'] = $this->config->item('service_tax')*100;
        // 获取所有的产品类型
        $data['cates'] = $this->category_m->get_cates_by_pid(0);
        $this->load->view('order_create', $data);
    }


    /**
     * 创建订单号
     * @return string
     */
    public function create_order_no(){
        $order_number = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        return $order_number;
    }

    public function pay_order($order_no){

        if(!$order_no){ return false;}
        // 根据订单号获取订单
        $order = $this->order_m->get_shop_orders_by_order_no($order_no);
        if($order['order_pay'] == 1 ){
            show_message('订单已经支付了哦！',site_url(V_URL.'orders/index/'),1);
            exit();
        }
        $notice = "含 ：";
        if($order['is_kaipiao'] == 1){
            $notice .= "10%税点, ";
        }
        // 送货费
        if($order['is_songhuo'] == 1){
            $notice .= $order['songhuo_fee']."送货费, ";
        }
        // 固定服务费
        $notice .= "2%服务费";
        $data['notice'] = $notice;
        $data['order'] = $order;
        $member = $this->user_m->get_user_by_user_id($this->uid);
        $data['member'] = $member;
//        pp($data);exit();
        $this->load->view('order_pay', $data);
    }
    public function pay_order_do(){

        $user_id = $this->session->userdata('user_id');
        $post = $this->input->post();
        $order_no = $post['order_no'];
        $pay_type = $post['pay_type'];//1销售贷2线下支付

        $order_info = $this->order_m->get_shop_orders_by_order_no($order_no);
        if($order_info['order_pay'] == 1 && $order_info['order_status'] > 0){
            echo json_encode(array('status' => 500,"msg"=>"该订单已经支付过了","url"=>site_url(V_URL."orders/records")));
            exit();
        }
        if($order_info['user_id'] == $user_id){
            // 获取余额信息
            $user_info=$this->user_m->get_user_by_user_id($user_id);
            $data = array(
                'order_pay'=>1,
                'order_status'=>2,
                'order_pay_type'=>$pay_type,
            );
            if($pay_type == 1){
                if($user_info['user_card_rz'] < 2){
                    echo json_encode(array('status' => 400,"msg"=>"您还没有开通销售贷"));
                    exit();
                }
                if($user_info['user_money_real']*100 < $order_info['order_price']*100){
                    echo json_encode(array('status' => 400,"msg"=>"销售贷余额不足"));
                    exit();
                }
            }
            $return = $this->order_m->sava_shop_orders_by_no($order_no,$data);
            if($return){
                if($pay_type == 1){
                    // 销售贷
                    $this->load->model('moneysale_m');
                    $this->load->model('moneylogs_m');
                    $rest = ($user_info['user_money_real']*100-$order_info['order_price']*100)/100;
                    $sale_log = array(
                        'user_id'=>$user_id,
                        'order_no'=>$order_no,
                        'order_cost'=>$order_info['order_price'],
                        'user_money_real'=>$rest,
                        'ctime'=>date("Y-m-d H:i:s"),
                    );
                    $this->moneysale_m->add_user_money_sale($sale_log);
                    // 变动日志
                    $money_log = array(
                        'user_id'=>$user_id,
                        'user_money_num'=>$order_info['order_price'],
                        'type'=>1,
                        'remark'=>"销售贷支付",
                        'ctime'=>date("Y-m-d H:i:s"),
                    );
                    $this->moneylogs_m->add_money_logs($money_log);
                    // 更新用户表余额
                    $this->user_m->update_user($user_id,array('user_money_real'=>$rest));
                }
                // 订单详情
                $tmporder_list = $this->tmporder_m->get_tmp_orders_by_order_no($order_no);
                $message_txt = "";
                if(!empty($tmporder_list)){
                    foreach ($tmporder_list as $k =>$v){
                        $good = $this->good_m->get_shop_goods_by_id($v['product_id']);
                        $message_txt = $good['good_title'].$good['good_memo']." ".$v['good_mum']."个;";
                    }
                }
                $massage = array(
                    'message_txt'=>"您已经成功下单 ".$message_txt,
                    'message_to_uid'=>$user_id,
                    'message_time'=>date("Y-m-d H:i:s"),
                );
                $this->message_m->add_massage($massage);
                echo json_encode(array(
                    'status' => 200,
                    "msg"=>"支付成功",
                    "url"=>site_url(V_URL."orders/order_success/".$order_no),
                ));
                exit();
            }else{
                echo json_encode(array('status' => 400,"msg"=>"支付失败"));
                exit();
            }
        }else{
            echo json_encode(array('status' => 400,"msg"=>"下单用户与当前用户不符合"));
            exit();
        }

    }

    public function order_success($order_no){

        if(!$order_no){ return false;}
        $order_info = $this->order_m->get_shop_orders_by_order_no($order_no);
        if(!empty($order_info)){
            $this->load->view('order_success');
        }else{
            return false;
        }

    }

    public function show_orders($id){

        $order_info = $this->order_m->get_shop_orders_by_id($id);
        $data['order'] = $order_info;
        // 分表数据
        $orders = $this->tmporder_m->get_tmp_orders_by_order_no($order_info['order_no']);
        if(!empty($orders)){
            foreach ($orders as $key => $val){
                $good = $this->good_m->get_shop_goods_by_id($val['product_id']);
                $orders[$key]['good_name'] = $good['good_title'];
                $orders[$key]['good_memo'] = $good['good_memo'];
                $orders[$key]['good_content'] = $good['good_content'];
                $orders[$key]['per_good_price'] = $good['good_price'];
            }
        }
        $data['order_list'] = $orders;
        // 地址
        $dress=$this->member_m->get_dress_by_dress_id($order_info['dress_id']);
        if(!empty($dress)){
            $area =  $this->areas_m->get_area_by_id($dress['dress_province']);
            $area2 =  $this->areas_m->get_area_by_id($dress['dress_city']);
            $area3 =  $this->areas_m->get_area_by_id($dress['dress_district']);
            $dress['dress_city'] = $area['area_name'].$area2['area_name'].$area3['area_name'];
        }
        $data['dress'] = $dress;

        $this->load->view('order_list', $data);

    }

    public function tanchuang(){

        $this->load->view('orders/tanchuang');
    }

    public function add_addr(){

        $post = $this->input->post();
        $data['user_id'] = $this->uid;
        $data['dress_uname'] = $post['dress_uname'];
        $data['dress_utel'] = $post['dress_utel'];
        $data['dress_province'] =$post['province'];
        $data['dress_city'] = $post['city'];
        $data['dress_district'] = $post['district'];
        $data['dress_udress'] = $post['address'];
        $data['dress_add_time'] = time();
        $data['dress_type'] = $post['dress_type'];
        if($post['dress_type'] == 1){
            $data1['dress_type']=0;
            $this->member_m->change_dress_by_user_id($this->uid,$data1);
            $this->member_m->add_dress($data);
        }else{
            $this->member_m->add_dress($data);
        }
        $dress=$this->member_m->get_address_by_uid($this->uid);
        if(!empty($dress)){
            foreach($dress as $key=>$val){
                $area =  $this->areas_m->get_area_by_id($val['dress_province']);
                $area2 =  $this->areas_m->get_area_by_id($val['dress_city']);
                $area3 =  $this->areas_m->get_area_by_id($val['dress_district']);
                $dress[$key]['dress_city'] = $area['area_name'].$area2['area_name'].$area3['area_name'];
            }
        }
        echo json_encode(['code' => 200, 'msg' => '新增地址成功',"data"=>$dress]);exit();
    }
    public function records($page = 1){

        $user_id = $this->session->userdata('user_id');
        $this->load->library('pagination');
        $limit = 20;
        $config['uri_segment'] = 4;
        // $page = !empty($config['uri_segment'])?$config['uri_segment']:'0';
        $config['use_page_numbers'] = TRUE;
        $config['base_url'] = site_url('manage/orders/index/');
        $config['total_rows'] = $this->db->count_all('shop_orders');
        $config['per_page'] = $limit;
        $config['num_links'] = 10;
        $this->pagination->initialize($config);
        $start = ($page-1)*$limit;
        $data['pagination'] = $this->pagination->create_links();
        $orders = $this->order_m->get_all_orders_mobile($start,$limit,$user_id);
        if(!empty($orders)){
            foreach ($orders as $key=>$val){
                $notice = "含 ：";
                if($val['is_kaipiao'] == 1){
                    $notice .= "10%税点, ";
                }
                if($val['is_songhuo'] == 1){
                    $notice .= $val['songhuo_fee']."送货费, ";
                }
                $notice .= "2%服务费";
                $orders[$key]['notice'] = $notice;
                // 订单详情
                $tmporder_list = $this->tmporder_m->get_tmp_orders_by_order_no($val['order_no']);
                if(!empty($tmporder_list)){
                    foreach ($tmporder_list as $k =>$v){
                        $cateinfo=$this->category_m->get_category_by_id($v['category_id']);
                        $tmporder_list[$k]['category_name'] =  $cateinfo['category_name'];
                        $good = $this->good_m->get_shop_goods_by_id($v['product_id']);
                        $tmporder_list[$k]['good_title'] = $good['good_title'];
                        $tmporder_list[$k]['good_memo'] = $good['good_memo'];
                        $tmporder_list[$k]['good_content'] = $good['good_content'];
                        $tmporder_list[$k]['per_good_price'] = $good['good_price'];
                        $tmporder_list[$k]['good_part_number'] = $good['good_part_number'];
                    }
                }
                $orders[$key]['tmp_list'] = $tmporder_list;
            }
        }
        $data['orders'] = $orders;
//        pp($orders);exit();
        $this->load->view('order_list', $data);
    }


}
